<template>
	<view class="page">
		<view class="header">
			<view class="main-tabs border-b d-b-c d-r">
				<view v-for="(tab, i) in mainTabs" :key="i" class="main-tab flex-1"
					:class="{ active: activeMainTab === i }" @click="switchMain(i)" ref="mainTabs">
					{{ tab.label }}<text v-if="tab.count">({{ tab.count }})</text>
				</view>
			</view>
			<view class="cats ml20">
				<view v-for="(c, idx) in categories" :key="idx" class="cat-pill" :class="{ active: activeCat === idx }"
					@click="switchCat(idx,c.categoryId)">
					{{ c.name }}
				</view>
			</view>
		</view>

		<!-- 数据列表 -->
		<scroll-view scroll-y="true" class=" list" lower-threshold="50" @scrolltoupper="scrolltoupperFunc"
			@scrolltolower="scrolltolowerFunc">

			<view class="list-item  " v-for="(item,index) in listData" :key="index">
				<view class="d-b-c d-r" @click="gotoPage('/pages/product/detail/detail?productId='+item.productId)">
					<image class="thumb mr10" :src="item.imagePath||'/static/default.png'" mode="aspectFill" />
					<view class="info d-s-s d-c flex-1 ml10">
						<text class="title" number-of-lines="2">{{ item.productName }}</text>
						<text class="prices f22">赚￥{{ item.money }}</text>
						<view class="bottom-row d-b-c d-r ww100">
							<text class="price">¥{{ item.productPrice }}</text>

						</view>
					</view>
				</view>
				<view class="d-e-c d-r">
					<view class="btn-earn1 mr10" @click="showShare(item)">
						<text class="icon iconfont icon-fenxiang1"></text>
						<text class="ml10">分享</text>
					</view>
					<view class="btn-earn">
						<text v-if="type==1" @click.stop="joins(item.productId)">加入推广</text>
						<text v-if="type==2" @click.stop="delects(item.productId)">删除</text>
					</view>
				</view>
			</view>

			<view class="d-c-c p30" v-if="listData.length == 0 && !loading">
				<text class="iconfont icon-wushuju"></text>
				<text class="cont">亲，暂无相关记录哦</text>
			</view>
			<uni-load-more v-else :loadingType="loadingType"></uni-load-more>
		</scroll-view>
		<!--底部弹窗-->
		<share :isbottmpanel="isbottmpanel" :productId="productId" @close="closeBottmpanel"></share>
		<!--app分享-->
		<AppShare :isAppShare="isAppShare" :appParams="appParams" @close="closeAppShare"></AppShare>
		<!--生成图片-->
		<uniPopup :show="isCreatedImg" type="middle" @hidePopup="hidePopupFunc">
			<view class="d-c-c d-c create-img">
				<image lazy-load :src="poster_img" mode="widthFix"></image>
				<!-- #ifdef MP -->
				<button class="btn-red mt20" type="default" @click="savePosterImg">保存图片</button>
				<!-- #endif  -->
				<!-- #ifdef H5 -->
				<view class="mt20 f34 red" type="default">长按保存图片</view>
				<!-- #endif -->
			</view>
		</uniPopup>
	</view>
</template>

<script>
	import uniLoadMore from '@/components/uni-load-more.vue';
	import uniPopup from '@/components/uni-popup.vue';
	import AppShare from '@/components/app-share.vue';
	import share from './share.vue';
	import utils from '@/common/utils.js';
	export default {
		components: {
			uniLoadMore,
			share,
			AppShare,
			uniPopup,
			utils
		},
		data() {
			return {
				appParams: {
					title: '',
					summary: '',
					path: ''
				},
				/*分享*/
				isbottmpanel: false,
				/*是否生成图片*/
				isCreatedImg: false,
				poster_img: '',
				isAppShare: false,
				mainTabs: [{
						label: '我的推广',
						count: 0
					},
					{
						label: '推广商品',
						count: 0
					}
				],
				activeMainTab: 0,
				mainTabWidth: 0,

				categories: [],
				activeCat: 0,
				/*当前第几页*/
				page: 1,
				/*一页多少条*/
				last_page: 0,
				list_rows: 10,
				listData: [],
				no_more: false,
				loading: false,
				allLoaded: false,
				tabWidths: [], // 每个 tab 的宽度
				tabLefts: [], // 每个 tab 的左偏移
				type: 2,
				categoryId: 0,
				/*手机高度*/
				phoneHeight: 0,
				/*可滚动视图区域高度*/
				scrollviewHigh: 10,
				productId: null,
				shareData: null,
				urldata: '',
			};
		},
		computed: {
			/*加载中状态*/
			loadingType() {
				if (this.loading) {
					return 1;
				} else {
					if (this.listData.length != 0 && this.no_more) {
						return 2;
					} else {
						return 0;
					}
				}
			}
		},
		mounted() {
			/*初始化*/
			// this.init();
		},
		onLoad(e) {
			//#ifdef H5
			if (this.isWeixin()) {
				this.urldata = window.location.href;
			}
			//#endif
		},
		onReady() {
			uni.setNavigationBarColor({
				frontColor: '#000000',
				backgroundColor: '#F5F5F5'
			});
		},
		onShareAppMessage(e) {
			let self = this;
			let item = self.shareData || {};
			let {
				productId,
				productName,
				productImage
			} = item;
			// 构建页面参数
			let params = self.getShareUrlParams({
				productId: productId,
				refereeId: self.getUserId(),
			});
			return {
				title: productName,
				path: "/pages/product/detail/detail?" + params,
				imageUrl: productImage,
			};
		},
		onShow() {
			uni.showLoading({
				title: '加载中'
			});
			this.listData = [];
			/*获取个人中心数据*/
			this.getData();
		},
		methods: {
			//关闭生成图片
			hidePopupFunc() {
				this.isCreatedImg = false;
			},
			showShare(e) {
				let self = this;
				self.shareData = e;
				self.productId = e.productId;
				//#ifndef APP-PLUS
				self.isbottmpanel = true;
				//#endif
				//#ifdef APP-PLUS
				self.appParams.title = e.product_name;
				self.appParams.summary = e.product_name;
				// 构建页面参数
				let params = self.getShareUrlParams({
					productId: self.productId
				});
				self.appParams.path = '/pages/product/detail/detail?' + params;
				self.appParams.image = e.product_image;
				self.isAppShare = true;
				//#endif
				self.taskFunc();
			},
			taskFunc() {
				let self = this;
				self._post(
					'plus/task/task/dayTask', {
						task_type: 'product'
					},
					res => {
						console.log('分享成功');
					}
				);
			},
			//关闭分享
			closeBottmpanel(data) {
				this.isbottmpanel = false;
				if (data.type == 2) {

					this.poster_img = data.poster_img;
					console.log(this.poster_img, 'poster_img')
					this.isCreatedImg = true;
				}
			},
			//关闭分享
			closeAppShare(data) {
				this.isAppShare = false;
			},
			savePosterImg() {
				let self = this;
				uni.showLoading({
					title: '加载中'
				});
				// 下载海报图片
				uni.downloadFile({
					url: self.poster_img,
					success(res) {
						uni.hideLoading();
						// 图片保存到本地
						uni.saveImageToPhotosAlbum({
							filePath: res.tempFilePath,
							success(data) {
								uni.showToast({
									title: '保存成功',
									icon: 'success',
									duration: 2000
								});
								// 关闭商品海报
								self.isCreatedImg = false;
							},
							fail(err) {
								if (err.errMsg === 'saveImageToPhotosAlbum:fail auth deny') {
									uni.showToast({
										title: '请允许访问相册后重试',
										icon: 'none',
										duration: 1000
									});
									setTimeout(() => {
										uni.openSetting();
									}, 1000);
								}
							},
							complete(res) {
								console.log('complete');
							}
						});
					}
				});
			},
			joins(id) {
				let self = this;
				self._post('plus/agent/agent/addProduct', {
					productId: id
				}, function(data) {
					uni.showToast({
						title: '加入成功',
						icon: 'success',
						duration: 2000
					});
					self.listData = [];
					self.getData();
					uni.hideLoading();

				});
			},
			delects(id) {
				let self = this;
				self._post('plus/agent/agent/delProduct', {
					id: id
				}, function(data) {
					uni.showToast({
						title: '删除成功',
						icon: 'success',
						duration: 2000
					});
					self.listData = [];
					self.getData();
					uni.hideLoading();


				});
			},
			/*初始化*/
			init() {
				let self = this;
				uni.getSystemInfo({
					success(res) {
						self.phoneHeight = res.windowHeight;
						// 计算组件的高度
						let view = uni.createSelectorQuery().select('.main-tabs');
						view.boundingClientRect(data => {
							let h = self.phoneHeight - data.height;
							self.scrollviewHigh = h;
						}).exec();
					}
				});
			},
			/*可滚动视图区域到底触发*/
			scrolltolowerFunc() {
				let self = this;
				console.log('111', self.no_more);
				if (self.no_more) {
					return;
				}
				self.page++;
				console.log('滚动视图区域到底部');
				if (self.page <= self.last_page) {
					self.getData();
				} else {
					self.no_more = true;
				}
			},
			/*可滚动视图区域到顶触发*/
			scrolltoupperFunc() {
				console.log('滚动视图区域到顶');
			},
			getData() {
				let self = this;
				self.loading = true;
				let params = {};
				params.type = self.type;
				params.categoryId = self.categoryId;
				params.pageIndex = self.page;
				params.pageSize = self.list_rows;
				params.url = self.urldata;
				self._postBody('plus/agent/agent/productList', params, function(res) {
					self.loading = false;
					self.listData = self.listData.concat(res.data.list.records);
					self.mainTabs[0].count = res.data.productNum.myNum;
					self.mainTabs[1].count = res.data.productNum.agentNum;
					const cats = res.data.category.slice();
					cats.unshift({
						name: '全部',
						categoryId: 0
					});
					self.categories = cats;
					self.last_page = res.data.list.lastPage;
					if (self.last_page <= 1) {
						self.no_more = true;
						return false;
					}
					uni.hideLoading();
				});
			},
			switchMain(i) {
				this.activeMainTab = i;
				this.type = i === 0 ? 2 : 1;
				this.categoryId = 0;
				this.no_more = false;
				this.page = 1;
				this.listData = [];
				this.getData();
			},
			switchCat(idx, id) {
				this.activeCat = idx;
				this.categoryId = id;
				this.no_more = false;
				this.page = 1;
				this.listData = [];
				this.getData();
			},

			loadMore() {
				if (this.allLoaded) return;
				// TODO: 拉取更多
				setTimeout(() => {
					this.allLoaded = true;
				}, 800);
			}
		}
	};
</script>

<style lang="scss" scoped>
	.page {
		position: relative;
		height: 100vh;
		overflow: hidden;
		width: 750rpx;

		background: #f9f9f9;
	}

	.header {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		height: 200rpx;
		background: #fff;
		z-index: 10;
	}

	/* 顶部主 Tabs */
	.main-tabs {
		background: #fff;
		text-align: center;
	}

	/* 将 flex-1 换成 inline-block，让宽度包裹内容 */
	.main-tab {
		position: relative;
		display: inline-block;
		/* 自动包裹文字+padding */
		padding: 0 30rpx;
		/* 注意左右内边距一致 */
		line-height: 88rpx;
		font-size: 30rpx;
		color: #666666;
		white-space: nowrap;

		/* 默认隐藏下划线 */
		&::after {
			content: "";
			position: absolute;
			bottom: 0;
			left: 50%;
			transform: translateX(-50%);
			width: 152rpx;
			height: 6rpx;
			background: linear-gradient(0deg, #FFDCA2 0%, #FDC57A 100%);
			opacity: 0;
			transition: opacity 0.2s;
		}

		/* 激活时显示下划线，并且文字变色 */
		&.active {
			color: #5A3713;
		}

		&.active::after {
			opacity: 1;
		}
	}

	/* 分类 Pills */
	.cats {
		display: flex;
		flex-wrap: nowrap;
		justify-content: flex-start;
		align-items: center;
		background: #fff;
		padding: 20rpx 0;
		margin-bottom: 20rpx;
		overflow-x: auto;
	}

	.cat-pill {
		font-size: 26rpx;
		color: #333;
		padding: 12rpx 30rpx;
		background: #fff;
		border-radius: 44rpx;
		white-space: nowrap;
	}

	.cat-pill.active {
		background: linear-gradient(0deg, #FFDCA2 0%, #FDC57A 100%);
		color: #5A3713;
	}


	/* 列表项 */
	.list {
		position: absolute;
		top: 200rpx;
		/* = .header 的高度 */
		bottom: 0;
		left: 0;
		right: 0;
		padding: 20rpx;
		box-sizing: border-box;




	}

	.list-item {


		background: #FFFFFF;
		border-radius: 20rpx;
		margin-bottom: 20rpx;
		padding: 20rpx;
	}

	.thumb {
		width: 164rpx;
		height: 164rpx;
		background: #FFFFFF;
		border-radius: 20rpx;


	}

	.info {
		flex: 1;
		justify-content: space-between;
	}

	.title {
		font-size: 28rpx;
		color: #333333;
		line-height: 40rpx;
	}

	.bottom-row {

		margin-top: 20rpx;
	}

	.price {
		font-size: 28rpx;
		font-weight: 600;
		color: #FF5649;
	}

	.btn-earn {
		min-width: 132rpx;
		background: linear-gradient(0deg, #FFDCA2 0%, #FDC57A 100%);
		border-radius: 28rpx;
		padding: 0 20rpx;
		font-size: 22rpx;
		color: #5A3713;
		height: 50rpx;
		line-height: 50rpx;
		box-sizing: border-box;
		text-align: center;
	}

	.btn-earn1 {
		min-width: 132rpx;
		height: 50rpx;
		line-height: 50rpx;
		padding: 0 26rpx;
		border-radius: 26rpx;
		border: 1px solid #EEEEEE;
		color: #54412C;
		box-sizing: border-box;
		text-align: center;

		.iconfont {
			color: #54412C;
			font-size: 22rpx;
		}
	}

	// 加载更多文本
	.load-more {
		text-align: center;
		color: #999999;
		font-size: 24rpx;
		padding: 30rpx 0;
	}

	.prices {
		line-height: 38rpx;
		background: #FDD4B6;
		border-radius: 10rpx;
		text-align: center;
		color: #5A3713;
		padding: 0 10rpx;
	}

	.create-img {
		width: 100%;
		padding: 20rpx;
		box-sizing: border-box;
	}

	.create-img image {
		width: 100%;

		border-radius: 20rpx;
	}

	.create-img button {
		width: 100%;
		height: 88rpx;
		line-height: 88rpx;
		border-radius: 44rpx;
		background: linear-gradient(0deg, #FFDCA2 0%, #FDC57A 100%);
	}
</style>